//
//  CNCommentToolbar.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2018/7/11.
//  Copyright © 2018年 CSDN. All rights reserved.
//

#import "CNCommentToolbar.h"
#import "CNBottomBar.h"
#import "CNViewConst.h"
#define TextViewHeight 66
@interface CNCommentToolbar ()<PPStickerKeyboardDelegate,UITextViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, assign, readwrite) CNKeyboardType keyboardType;

@property (nonatomic, strong) PPStickerKeyboard *stickerKeyboard;

@property (nonatomic, assign) BOOL keepsPreModeTextViewWillEdited;

@property(nonatomic, assign)CGFloat keyboardHeight;

@property(nonatomic , strong)UIView *inputMaskView;

@property(nonatomic , assign)CGFloat inputMaskViewHeight ;

@property(nonatomic, strong)UIButton *bgBtn;

@property (nonatomic, strong) UIView *inputToolView;

@property (nonatomic, strong) PPButton *sendButton;

@property (nonatomic, strong) NSArray *atUserArray;


@end

@implementation CNCommentToolbar
- (NSArray *)atUserArray{
    if (_atUserArray == nil) {
        _atUserArray = [NSArray array];
    }
    return _atUserArray;
}
- (id)init
{
    self = [super init];
    if (self) {
        
        self.contentMode = UIViewContentModeRedraw;
        self.exclusiveTouch = YES;
        self.backgroundColor = [UIColor clearColor];
        self.inputMaskViewHeight = 122;
        self.emojiToggleButton.hidden = NO;
        self.sendButton.hidden = NO;
        self.keyboardType = CNKeyboardTypeSystem;
        self.textView.hidden = NO;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}


-(UIView *)inputMaskView
{
    if (!_inputMaskView) {
        _inputMaskView = [[UIView alloc]init];
        _inputMaskView.theme_backgroundColor = menuPageBGColorPicker;
        [self addSubview:_inputMaskView];
        [_inputMaskView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo([UIScreen mainScreen].bounds.size.height-self.inputMaskViewHeight);
            make.left.mas_equalTo(self);
            make.width.mas_equalTo([[UIScreen mainScreen]bounds].size.width);
            make.height.mas_equalTo(self.inputMaskViewHeight);
        }];
        _inputMaskView.layer.theme_shadowColor = shadowsColorPicker;
        _inputMaskView.layer.shadowOffset = CGSizeMake(0, -0.5);
        _inputMaskView.layer.shadowOpacity = [CNThemesManager isNight]?1:0.15;
        _inputMaskView.layer.shadowRadius = 0;
//        UIView *lineView = [[UIView alloc]init];
//        lineView.theme_backgroundColor = bbsSectionLineColorPicker;
//        [self.inputMaskView addSubview:lineView];
//        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.top.mas_equalTo(0);
//            make.height.mas_equalTo(0.5);
//        }];
    }
    return _inputMaskView;
}

- (PPButton *)emojiToggleButton
{
    if (!_emojiToggleButton) {
        _emojiToggleButton = [[PPButton alloc] init];
        [_emojiToggleButton theme_setImage:dynamicEmojiImage forState:UIControlStateNormal];
        [_emojiToggleButton theme_setImage:dynamicEmojiImage forState:UIControlStateHighlighted];
//        _emojiToggleButton.touchInsets = UIEdgeInsetsMake(-12, -20, -12, -20);
        [_emojiToggleButton addTarget:self action:@selector(toggleKeyboardDidClick:) forControlEvents:UIControlEventTouchUpInside];
        _emojiToggleButton.tag = CNCommentToolbarButtonTypeEmotion;
        [self.inputMaskView addSubview:_emojiToggleButton];
        [_emojiToggleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(0);
            make.left.mas_equalTo(16);
            make.size.mas_equalTo(CGSizeMake(44, 44));
            
        }];
    }
    return _emojiToggleButton;
}
- (PPButton *)atButton{
    if (!_atButton) {
        _atButton = [[PPButton alloc] init];
        [_atButton theme_setImage:dynamicATImage forState:UIControlStateNormal];
        [_atButton theme_setImage:dynamicATImage forState:UIControlStateHighlighted];
        [self.inputMaskView addSubview:_atButton];
//        _atButton.touchInsets = UIEdgeInsetsMake(-12, -20, -12, -20);
        [_atButton addTarget:self action:@selector(clickAtButton) forControlEvents:UIControlEventTouchUpInside];

        [_atButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(0);
            make.left.mas_equalTo(16);
            make.size.mas_equalTo(CGSizeMake(44, 44));
        }];
        _atButton.hidden = YES;

    }
    return _atButton;
}
- (PPButton *)sendButton{
    if (!_sendButton) {
        _sendButton = [[PPButton alloc] init];
        [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
//        _sendButton.touchInsets = UIEdgeInsetsMake(-12, -20, -12, -20);
//        _sendButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _sendButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_sendButton setTitleColor:[UIColor colorFromHexCode:@"#4788c7"] forState:UIControlStateNormal];
        [_sendButton setTitleColor: [CNThemesManager isNight]?[UIColor colorFromHexCode:@"#484b54"]:[UIColor colorFromHexCode:@"#d9d9de"] forState:UIControlStateDisabled];
        
        [_sendButton addTarget:self action:@selector(commentToolbarDidClickSendButton) forControlEvents:UIControlEventTouchUpInside];
        _sendButton.enabled = NO;
        [self.inputMaskView addSubview:_sendButton];
        [_sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-16);
            make.bottom.mas_equalTo(0);
            make.height.mas_equalTo(44);
            make.width.mas_equalTo(44);
        }];
    }
    return _sendButton;
}
-(PPStickerTextView *)textView
{
    if (!_textView) {
        _textView = [[PPStickerTextView alloc]init];
        _textView.theme_backgroundColor = newSearchBarBGPickerColor;
        _textView.textContainerInset = UIEdgeInsetsMake(0,-5, 0, 0);
        _textView.delegate = self;
        _textView.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _textView.keyboardAppearance = [CNThemesManager isNight] ? UIKeyboardAppearanceDark : UIKeyboardAppearanceDefault;
        _textView.showsVerticalScrollIndicator = YES;
        _textView.placeholderColor = cellDesTitleTextColor;
//        _textView.placeholderColor = [CNThemesManager isNight] ? commentPlaceholderNightTextColor : commentPlaceholderTextColor;
        _textView.theme_textColor = cellTitleTextColorPicker;
        _textView.placeholder = @"写评论";
        _textView.scrollsToTop = NO;
        _textView.scrollEnabled = NO ;
        _textView.returnKeyType = UIReturnKeyDefault;
        _textView.enablesReturnKeyAutomatically = YES;
        if (@available(iOS 11.0, *)) {
            _textView.textDragInteraction.enabled = NO;
        }
        _textView.font = [UIFont systemFontOfSize:14];
//        _textView.theme_tintColor = cellTitleTextColorPicker;
        _textView.textContainerInset = UIEdgeInsetsMake(8,8,8,0);
        _textView.layer.cornerRadius = 8 ;
        _textView.layer.borderWidth = 0.5;
        _textView.layer.borderColor = [CNThemesManager isNight] ? [UIColor clearColor].CGColor : commentBordCGColor.CGColor;
        _textView.layer.masksToBounds = YES ;
        @weakify(self);
//        [_textView addTapGestureWithBlock:^(UIView *gestureView) {
//            @strongify(self);
//            [self changeKeyboardTo:CNKeyboardTypeSystem];
//        }];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(inputTextViewDidClick)];
        tapGesture.delegate = self;
        [_textView addGestureRecognizer:tapGesture];
        [self.inputMaskView addSubview:_textView];
        [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(16);
            make.right.mas_equalTo(-16);
            make.top.mas_equalTo(8);
            make.bottom.mas_equalTo(-44);
        }];
    }
    return _textView;
}

- (PPStickerKeyboard *)stickerKeyboard
{
    if (!_stickerKeyboard) {
        _stickerKeyboard = [[PPStickerKeyboard alloc] init];
        _stickerKeyboard.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), [self.stickerKeyboard heightThatFits]);
        _stickerKeyboard.delegate = self;
        _stickerKeyboard.sendButton.hidden = YES;
//        [_stickerKeyboard.sendButton setTitle:@"发送" forState:(UIControlStateNormal)];
    }
    return _stickerKeyboard;
}

- (void)toggleKeyboardDidClick:(UIButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(commentToolbar:didClickButton:)]) {
        [self.delegate commentToolbar:self didClickButton:(int)sender.tag];
    }
    [self changeKeyboardTo:(self.keyboardType == CNKeyboardTypeSystem ? CNKeyboardTypeSticker : CNKeyboardTypeSystem)];
}

- (void)pictureButtonDidClick:(UIButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(commentToolbar:didClickButton:)]) {
        [self.delegate commentToolbar:self didClickButton:(int)sender.tag];
    }
}
- (void)clickAtButton{
    if (self.delegate && [self.delegate respondsToSelector:@selector(commentToolbarDidClinkAtButton:)]) {
        [self.delegate commentToolbarDidClinkAtButton:self];
    }
}

#pragma mark -gesture
- (void)inputTextViewDidClick{
    [self changeKeyboardTo:CNKeyboardTypeSystem];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

- (void)changeKeyboardTo:(CNKeyboardType)toType
{
    if (self.keyboardType == toType) {
        return;
    }
    
    switch (toType) {
        case CNKeyboardTypeNone:
            [self.emojiToggleButton theme_setImage:dynamicEmojiImage forState:UIControlStateNormal];
            self.textView.inputView = nil;
            break;
        case CNKeyboardTypeSystem:
            [self.emojiToggleButton theme_setImage:dynamicEmojiImage forState:UIControlStateNormal];
            self.textView.inputView = nil;                          // 切换到系统键盘
            [self.textView reloadInputViews];                       // 调用reloadInputViews方法会立刻进行键盘的切换
            break;
        case CNKeyboardTypeSticker:
            [self.emojiToggleButton theme_setImage:dynamicEmojiSelectImage forState:UIControlStateNormal];
            self.textView.inputView = self.stickerKeyboard;         // 切换到自定义的表情键盘
            [self.textView reloadInputViews];
            break;
        default:
            break;
    }
    
    self.keyboardType = toType;
    [self.textView becomeFirstResponder];
}

#pragma mark -- 显示和隐藏
- (void)setAtButtonHidden:(BOOL)hidden{
    self.atButton.hidden = hidden;
    if (hidden) {
        [self.emojiToggleButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(16);
        }];
    }else{
        [self.emojiToggleButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(76);
        }];
        
        [self.emojiToggleButton theme_setImage:dynamicEmojiImage forState:UIControlStateNormal];
        [self.emojiToggleButton theme_setImage:dynamicEmojiImage forState:UIControlStateHighlighted];
    }
   
}

- (void)showKeyBoard
{
    [self removeFromSuperview];
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(0);
        make.size.mas_equalTo([UIScreen mainScreen].bounds.size);
    }];
    [self layoutIfNeeded];
    [self.textView becomeFirstResponder];
}

#pragma mark - Keyboard

- (void)keyboardWillShow:(NSNotification *)notification
{
    if ([self.textView isFirstResponder]) {
        NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:notification.userInfo];
        // 获取键盘高度
        CGRect keyBoardBounds  = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        self.keyboardHeight = keyBoardBounds.size.height;
        // 获取键盘动画时间
        CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
        
        void (^animation)(void) = ^void(void) {
            self.inputMaskView.transform = CGAffineTransformMakeTranslation(0, - self.keyboardHeight);
        };
        
        if (animationTime > 0) {
            [UIView animateWithDuration:animationTime animations:animation];
            self.hidden = NO;
        } else {
            animation();
        }
    }
    
   
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    if (self.textView.isFirstResponder) {
        NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:notification.userInfo];
        // 获取键盘动画时间
        CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
        // 获取键盘高度
        CGRect keyBoardBounds  = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat keyBoardHeight = keyBoardBounds.size.height;
        
        void (^animation)(void) = ^void(void) {
            self.inputMaskView.transform = CGAffineTransformMakeTranslation(0, keyBoardHeight + self.inputMaskView.frame.size.height);
        };
        
        if (animationTime > 0) {
            [UIView animateWithDuration:animationTime animations:animation completion:^(BOOL finished) {
                //self.delegate = nil ;
                //[self removeFromSuperview];
                self.hidden = YES;
            }];
        } else {
            animation();
        }
    }
   
}

#pragma mark -- 设置输入视图的高度及Y坐标

- (void)adjustInputView{
    
    self.textView.scrollEnabled = NO ;
    
    CGSize size = [self.textView sizeThatFits:CGSizeMake(self.textView.frame.size.width,MAXFLOAT)];
    CGFloat height = fmax(TextViewHeight, size.height);
    if(height > (8 * self.textView.font.lineHeight + 16)){
        height = (8 * self.textView.font.lineHeight + 16);
        self.textView.scrollEnabled = YES ;
    }
    [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];
    
    height = height + self.inputMaskViewHeight - TextViewHeight ;
    [self.inputMaskView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.keyboardHeight + [UIScreen mainScreen].bounds.size.height - self.keyboardHeight - height);
        make.height.mas_equalTo(height);
    }];
    
    [self.inputMaskView layoutIfNeeded];
}

#pragma mark - public method

- (void)clearText
{
    self.textView.text = nil;
    [self adjustInputView];
}

#pragma mark - TextFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
   
}

#pragma TextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.keepsPreModeTextViewWillEdited = NO;
    [self.inputView changeKeyboardTo:CNKeyboardTypeSystem];
    
    if ([self.delegate respondsToSelector:@selector(commentToolbarShouldBeginEditing:)]) {
        return [self.delegate commentToolbarShouldBeginEditing:self];
    } else {
        return YES;
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    self.keepsPreModeTextViewWillEdited = YES;
    if ([self.delegate respondsToSelector:@selector(commentToolbarDidEndEditing:)]) {
        [self.delegate commentToolbarDidEndEditing:self];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
}

- (void)textViewDidChange:(UITextView *)textView
{
    [textView.superview layoutSubviews];
    [self refreshTextUI];
    
    [self.textView scrollRangeToVisible:self.textView.selectedRange];
    [self adjustInputView];
    if ([self.delegate respondsToSelector:@selector(commentToolbarDidChange:)]) {
        [self.delegate commentToolbarDidChange:self];
    }
    
    self.sendButton.enabled = textView.text.length > 0;
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ( [self.delegate isKindOfClass:[CNBottomBar class]]) {
        CNBottomBar *bottomBar = (CNBottomBar *)self.delegate;
        if (bottomBar.barType == CNBottomBarTypeBlinComment) {
            if (self.hideAt == YES) {
                return YES;
            }
            if([text isEqualToString:@"@"]){
                
                [self clickAtButton];
                return NO;
            }
        }
    }
   
//    if ([@"\n" isEqualToString:text]) {
//        if (self.delegate && [self.delegate respondsToSelector:@selector(commentToolbarDidClickSendButton:)]) {
//            [self.delegate commentToolbarDidClickSendButton:self];
//            [self.textView resignFirstResponder];
//        }
//
//        [self adjustInputView];
//
//        return NO;
//    }
    
    return YES;
}

#pragma mark - private method

- (void)refreshTextUI
{
    if (!self.textView.text.length) {
        return;
    }
    UITextRange *markedTextRange = [self.textView markedTextRange];
    UITextPosition *position = [self.textView positionFromPosition:markedTextRange.start offset:0];
    self.textView.theme_textColor = cellTitleTextColorPicker;
    if (position) {
        return;     // 正处于输入拼音还未点确定的中间状态
    }
    
    [self refreshTextViewWithText:self.plainText];
    
  
}
- (void)refreshTextViewWithText:(NSString *)text{
    
    NSRange selectedRange = self.textView.selectedRange;
    NSMutableAttributedString *attributedComment = [[NSMutableAttributedString alloc] initWithString:text attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:15], NSForegroundColorAttributeName: [CNThemesManager isNight] ? cellComNightTitleTextColor :cellComTitleTextColor }];
//    [CSDNConst addAtAttributeWithString:attributedComment];
        NSArray *atUserArray =  [CNViewConst addAtAttributeWithString:attributedComment];
        if(atUserArray.count > 0 ){
            self.atUserArray = atUserArray;

        }
    // 匹配表情
    [PPStickerDataManager.sharedInstance replaceEmojiForAttributedString:attributedComment font:[UIFont systemFontOfSize:15]];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 6;
    [attributedComment addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:attributedComment.pp_rangeOfAll];
    
    NSUInteger offset = self.textView.attributedText.length - attributedComment.length;
    self.textView.attributedText = attributedComment;
    self.textView.selectedRange = NSMakeRange(selectedRange.location - offset, 0);
    
    
 

  
    
}
- (NSString *)plainText
{
    
    NSString *str =[self.textView.attributedText pp_plainTextForRange:NSMakeRange(0, self.textView.attributedText.length)];
    // 反转@用户名格式
    str = [CNViewConst replaceAtUsername:str atUserArray:self.atUserArray];
    
    return str;

}
- (void)addText:(NSString *)text{
    [self refreshTextViewWithText:text];
    [self textViewDidChange:self.textView];
}


#pragma mark - PPStickerKeyboardDelegate

- (void)stickerKeyboard:(PPStickerKeyboard *)stickerKeyboard didClickEmoji:(PPEmoji *)emoji
{
    if (!emoji) {
        return;
    }
    
//    UIImage *emojiImage = [UIImage imageNamed:[@"Sticker.bundle" stringByAppendingPathComponent:emoji.imageName]];
    NSString *imageName = [[[NSBundle bundleForClass:[self class]] pathForResource:@"Sticker" ofType:@"bundle"] stringByAppendingPathComponent:emoji.imageName];
    UIImage *emojiImage = [UIImage imageWithContentsOfFile:imageName];
    if (!emojiImage) {
        return;
    }
    
    NSRange selectedRange = self.textView.selectedRange;
    NSString *emojiString = [NSString stringWithFormat:@"%@", emoji.emojiDescription];
    NSMutableAttributedString *emojiAttributedString = [[NSMutableAttributedString alloc] initWithString:emojiString];
    [emojiAttributedString pp_setTextBackedString:[PPTextBackedString stringWithString:emojiString] range:emojiAttributedString.pp_rangeOfAll];
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
    [attributedText replaceCharactersInRange:selectedRange withAttributedString:emojiAttributedString];
    self.textView.attributedText = attributedText;
    self.textView.selectedRange = NSMakeRange(selectedRange.location + emojiAttributedString.length, 0);
    
    [self.textView.delegate textViewDidChange:self.textView];
}

- (void)stickerKeyboardDidClickDeleteButton:(PPStickerKeyboard *)stickerKeyboard
{
    NSRange selectedRange = self.textView.selectedRange;
    if (selectedRange.location == 0 && selectedRange.length == 0) {
        return;
    }

    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
    if (selectedRange.length > 0) {
        [attributedText deleteCharactersInRange:selectedRange];
        self.textView.attributedText = attributedText;
        self.textView.selectedRange = NSMakeRange(selectedRange.location, 0);
    } else {
        NSUInteger deleteCharactersCount = 1;
        
        // 下面这段正则匹配是用来匹配文本中的所有系统自带的 emoji 表情，以确认删除按钮将要删除的是否是 emoji。这个正则匹配可以匹配绝大部分的 emoji，得到该 emoji 的正确的 length 值；不过会将某些 combined emoji（如 👨‍👩‍👧‍👦 👨‍👩‍👧‍👦 👨‍👨‍👧‍👧），这种几个 emoji 拼在一起的 combined emoji 则会被匹配成几个个体，删除时会把 combine emoji 拆成个体。瑕不掩瑜，大部分情况下表现正确，至少也不会出现删除 emoji 时崩溃的问题了。
        NSString *emojiPattern1 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900-\\U0001F9FF]";
        NSString *emojiPattern2 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900–\\U0001F9FF]\\uFE0F";
        NSString *emojiPattern3 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900–\\U0001F9FF][\\U0001F3FB-\\U0001F3FF]";
        NSString *emojiPattern4 = @"[\\rU0001F1E6-\\U0001F1FF][\\U0001F1E6-\\U0001F1FF]";
        NSString *pattern = [[NSString alloc] initWithFormat:@"%@|%@|%@|%@", emojiPattern4, emojiPattern3, emojiPattern2, emojiPattern1];
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:kNilOptions error:NULL];
        NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:attributedText.string options:kNilOptions range:NSMakeRange(0, attributedText.string.length)];
        for (NSTextCheckingResult *match in matches) {
            if (match.range.location + match.range.length == selectedRange.location) {
                deleteCharactersCount = match.range.length;
                break;
            }
        }
        
        [attributedText deleteCharactersInRange:NSMakeRange(selectedRange.location - deleteCharactersCount, deleteCharactersCount)];
        self.textView.attributedText = attributedText;
        self.textView.selectedRange = NSMakeRange(selectedRange.location - deleteCharactersCount, 0);
    }

    [self.textView.delegate textViewDidChange:self.textView];
}

- (void)stickerKeyboardDidClickSendButton:(PPStickerKeyboard *)stickerKeyboard
{
//    if (self.delegate && [self.delegate respondsToSelector:@selector(commentToolbarDidClickSendButton:)]) {
//        [self.delegate commentToolbarDidClickSendButton:self];
//    }
//    [self.textView resignFirstResponder];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    [self endEditing:YES];
    [self removeFromSuperview];
}
- (void)commentToolbarDidClickSendButton{
        if (self.delegate && [self.delegate respondsToSelector:@selector(commentToolbarDidClickSendButton:)]) {
            [self.delegate commentToolbarDidClickSendButton:self];
        }
        [self.textView resignFirstResponder];
        [self removeFromSuperview];

}
-(void)dealloc
{
    //在页面消失的回调方法中移除通知。
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
